package com.data.modules.quartz.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.data.common.api.vo.CrmResult;
import com.data.common.constant.CacheConstant;
import com.data.common.util.DateUtils;
import com.data.modules.emp.entity.AdminDeptVO;
import com.data.modules.feign.AdminService;
import com.data.modules.system.entity.SysDepart;
import com.data.modules.system.service.ISysDepartService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;


/**
 * emp RP-crm组织同步
 *
 * @author cmg
 * @since 2022/2/14
 */

@Slf4j
public class CrmDeptSyscJob implements Job {

    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;

    public void setParameter(String parameter) {
        if (ObjectUtils.isEmpty(parameter)) {
            DateTime dateTime = DateUtil.offsetMonth(new Date(), -1);
            parameter = DateUtil.format(dateTime, "yyyy-MM");
        }
        this.parameter = parameter;
    }

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    @Lazy
    private AdminService adminService;


    /**
     * emp RP-crm组织同步
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        /**
         * parameter
         */

        log.info("=======================【RP-crm组织同步开始】===================");
        log.info(" Job Execution key：" + jobExecutionContext.getJobDetail().getKey());
        log.info("welcome %s! Jeecg-Boot 带参数定时任务 SampleParamJob !   时间:{},参数：{}", DateUtils.now(), this.parameter);


        CrmResult<List<AdminDeptVO>> listCrmResult = adminService.queryRpDeptTreeAll(null);
        if (ObjectUtils.isEmpty(listCrmResult)) {
            log.info("远程加载crm-admin部门数据为空");
            return ;
        }
        List<AdminDeptVO> data = listCrmResult.getData();
        if (ObjectUtils.isEmpty(data)) {
            log.info("远程加载crm-admin员工数据为空");
            return ;
        }
        log.info("crm.admin提供的数据 data===>{}", JSON.toJSONString(data));

        // 递归同步部门
        this.syncAdminDeptVOmentToLocalRecursion(data, null,"amdin");

        log.info("=======================【RP-crm组织同步结束】===================");
    }


    /**
     * 递归同步部门到本地
     */
    private void syncAdminDeptVOmentToLocalRecursion(List<AdminDeptVO> departmentTreeList, String sysParentId,String username) {
        if (departmentTreeList != null && departmentTreeList.size() != 0) {
            for (AdminDeptVO departmentTree : departmentTreeList) {
                String depId = departmentTree.getId() + "";
                LambdaQueryWrapper<SysDepart> queryWrapper = new LambdaQueryWrapper<>();
                // 根据 qywxIdentifier 字段查询
                queryWrapper.eq(SysDepart::getId, depId);
                SysDepart sysDepart = sysDepartService.getOne(queryWrapper);
                if (sysDepart != null) {
                    //  执行更新操作
                    SysDepart updateSysDepart = this.qwDepartmentToSysDepart(departmentTree, sysDepart);
                    if (sysParentId != null) {
                        updateSysDepart.setParentId(sysParentId);
                    }
                    try {
                        sysDepartService.updateDepartDataById(updateSysDepart, username);
                        String str = String.format("部门 %s 更新成功！", updateSysDepart.getDepartName());
                        log.info(str);
                    } catch (Exception e) {
                        log.error("部门 更新成功！{}", e.getMessage());
                    }
                    if (ObjectUtil.isNotEmpty(departmentTree.getChildren())) {
                        // 紧接着同步子级
                        this.syncAdminDeptVOmentToLocalRecursion(departmentTree.getChildren(), updateSysDepart.getId(), username);
                    }
                } else {
                    // 执行新增操作
                    SysDepart newSysDepart = this.qwDepartmentToSysDepart(departmentTree, null);
                    newSysDepart.setCreateBy(username);
                    if (sysParentId != null) {
                        newSysDepart.setParentId(sysParentId);
                    }
                    try {
                        sysDepartService.saveDepartData(newSysDepart, username);
                        String str = String.format("部门 %s 创建成功！", newSysDepart.getDepartName());
                        log.info(str);
                    } catch (Exception e) {
                        log.error("=====部门 创建失败！====>{}", e.getMessage());
                    }
                    // 紧接着同步子级
                    if (ObjectUtil.isNotEmpty(departmentTree.getChildren()))  {
                        this.syncAdminDeptVOmentToLocalRecursion(departmentTree.getChildren(), newSysDepart.getId(), username);
                    }
                }
            }
        }
    }



    /**
     * 【同步部门】将crm的AdminDeptVO 对象转为SysDepart
     */
    private SysDepart qwDepartmentToSysDepart(AdminDeptVO department, SysDepart oldSysDepart) {
        SysDepart sysDepart = new SysDepart();
        if (oldSysDepart != null) {
            BeanUtils.copyProperties(oldSysDepart, sysDepart);
        }
        sysDepart.setId(department.getId().toString());
        sysDepart.setParentId(department.getPid().toString());
        sysDepart.setDepartName(department.getName());
        sysDepart.setDelFlag("0");
        return sysDepart;
    }
}
